<template>
  <div class="family-member-list">
    <div class="header">
      <h2>家族成员管理</h2>
      <a-button type="primary" @click="handleAdd">新增成员</a-button>
    </div>
    
    <!-- 选择家族树 -->
    <div class="family-tree-selector" style="margin-bottom: 20px;">
      <a-select 
        v-model:value="selectedFamilyTree" 
        placeholder="请选择家族树" 
        style="width: 300px;"
        @change="onFamilyTreeChange"
      >
        <a-select-option 
          v-for="tree in familyTreeStore.familyTrees" 
          :key="tree.id" 
          :value="tree.id"
        >
          {{ tree.name }}
        </a-select-option>
      </a-select>
      <a-button @click="refresh" style="margin-left: 10px;">刷新</a-button>
    </div>
    
    <a-table 
      :data-source="familyStore.members" 
      style="width: 100%" 
      :loading="loading"
    >
      <a-table-column key="id" title="ID" data-index="id" :width="80" />
      <a-table-column key="name" title="姓名" data-index="name" :width="120" />
      <a-table-column key="gender" title="性别" :width="80">
        <template #bodyCell="{ record }">
          <a-tag :color="record.gender === 'M' ? 'blue' : 'pink'">
            {{ record.gender === 'M' ? '男' : '女' }}
          </a-tag>
        </template>
      </a-table-column>
      <a-table-column key="birthDate" title="出生日期" :width="120">
        <template #bodyCell="{ record }">
          {{ formatDate(record.birthDate) }}
        </template>
      </a-table-column>
      <a-table-column key="deathDate" title="去世日期" :width="120">
        <template #bodyCell="{ record }">
          {{ formatDate(record.deathDate) }}
        </template>
      </a-table-column>
      <a-table-column key="familyTreeId" title="家族树ID" data-index="familyTreeId" :width="100" />
      <a-table-column key="actions" title="操作" :width="200">
        <template #bodyCell="{ record }">
          <a-button size="small" @click="handleEdit(record)">编辑</a-button>
          <a-button size="small" type="primary" @click="handleViewRelatives(record)">关系</a-button>
          <a-button size="small" danger @click="handleDelete(record)">删除</a-button>
        </template>
      </a-table-column>
    </a-table>
    
    <!-- 关系图谱对话框 -->
    <a-modal v-model:open="dialogVisible" title="成员关系图谱" width="60%">
      <div v-if="selectedMember" class="member-info">
        <h3>{{ selectedMember.name }} 的关系图谱</h3>
        <a-descriptions :column="2" bordered>
          <a-descriptions-item label="父亲">
            {{ relatives.father ? relatives.father.name : '未设置' }}
          </a-descriptions-item>
          <a-descriptions-item label="母亲">
            {{ relatives.mother ? relatives.mother.name : '未设置' }}
          </a-descriptions-item>
          <a-descriptions-item label="配偶">
            {{ relatives.spouse ? relatives.spouse.name : '未设置' }}
          </a-descriptions-item>
        </a-descriptions>
        
        <div class="children-section" v-if="relatives.children && relatives.children.length > 0">
          <h4>子女</h4>
          <a-table :data-source="relatives.children" style="width: 100%">
            <a-table-column key="name" title="姓名" data-index="name" />
            <a-table-column key="gender" title="性别">
              <template #bodyCell="{ record }">
                {{ record.gender === 'M' ? '男' : '女' }}
              </template>
            </a-table-column>
            <a-table-column key="birthDate" title="出生日期">
              <template #bodyCell="{ record }">
                {{ formatDate(record.birthDate) }}
              </template>
            </a-table-column>
          </a-table>
        </div>
      </div>
      
      <template #footer>
        <a-button @click="dialogVisible = false">关闭</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script>
import { ref, watch, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { message, Modal } from 'ant-design-vue'
import { useFamilyStore } from '../stores/family'
import { useFamilyTreeStore } from '../stores/familyTree'
import api from '../api'

export default {
  name: 'FamilyMemberList',
  setup() {
    const router = useRouter()
    const familyStore = useFamilyStore()
    const familyTreeStore = useFamilyTreeStore()
    const dialogVisible = ref(false)
    const selectedMember = ref(null)
    const loading = ref(false)
    const selectedFamilyTree = ref(null)
    
    // 获取家族树列表
    const { refetch: fetchFamilyTrees } = familyTreeStore.useFetchFamilyTrees()
    
    // 获取成员列表
    const { loading: fetchLoading, refetch: refetchMembers } = familyStore.useFetchMembersByFamilyTree()
    
    // 关系数据
    const relatives = ref({
      father: null,
      mother: null,
      spouse: null,
      children: []
    })
    
    // 更新加载状态
    watch(fetchLoading, (newVal) => {
      loading.value = newVal.value
    })
    
    // 家族树变更时的处理
    const onFamilyTreeChange = async (familyTreeId) => {
      familyStore.setSelectedFamilyTree(familyTreeId)
      try {
        await refetchMembers()
      } catch (error) {
        message.error('获取成员列表失败')
        console.error('获取成员列表失败:', error)
      }
    }
    
    // 刷新数据
    const refresh = async () => {
      try {
        await fetchFamilyTrees()
        if (selectedFamilyTree.value) {
          await refetchMembers()
        }
      } catch (error) {
        message.error('刷新数据失败')
        console.error('刷新数据失败:', error)
      }
    }
    
    // 组件挂载时获取家族树列表
    onMounted(async () => {
      try {
        await fetchFamilyTrees()
        // 如果有家族树，默认选择第一个
        if (familyTreeStore.familyTrees.length > 0 && !selectedFamilyTree.value) {
          selectedFamilyTree.value = familyTreeStore.familyTrees[0].id
          familyStore.setSelectedFamilyTree(selectedFamilyTree.value)
          await refetchMembers()
        }
      } catch (error) {
        message.error('获取家族树列表失败')
        console.error('获取家族树列表失败:', error)
      }
    })
    
    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleDateString('zh-CN')
    }
    
    // 新增成员
    const handleAdd = () => {
      // 添加成员时需要指定家族树
      if (!selectedFamilyTree.value) {
        message.warning('请先选择一个家族树')
        return
      }
      router.push({
        path: '/family-members/new',
        query: { familyTreeId: selectedFamilyTree.value }
      })
    }
    
    // 编辑成员
    const handleEdit = (row) => {
      router.push(`/family-members/${row.id}`)
    }
    
    // 查看关系
    const handleViewRelatives = async (row) => {
      try {
        selectedMember.value = row
        // 重置关系数据
        relatives.value = {
          father: null,
          mother: null,
          spouse: null,
          children: []
        }
        
        // 获取直系亲属
        const response = await api.get(`/members/${row.id}/relatives`)
        const relativesData = response.data.data || []
        
        // 分类处理关系数据
        const newRelatives = {
          father: null,
          mother: null,
          spouse: null,
          children: []
        }
        
        relativesData.forEach(member => {
          if (member.id === row.fatherId) {
            newRelatives.father = member
          } else if (member.id === row.motherId) {
            newRelatives.mother = member
          } else if (member.id === row.spouseId) {
            newRelatives.spouse = member
          } else if (member.fatherId === row.id || member.motherId === row.id) {
            newRelatives.children.push(member)
          }
        })
        
        relatives.value = newRelatives
        dialogVisible.value = true
      } catch (error) {
        message.error('获取关系信息失败')
        console.error('获取关系信息失败:', error)
      }
    }
    
    // 删除成员
    const handleDelete = (row) => {
      Modal.confirm({
        title: '确认删除',
        content: `确定要删除成员 "${row.name}" 吗？此操作不可恢复！`,
        okText: '确定',
        cancelText: '取消',
        onOk: async () => {
          try {
            const { mutateAsync: deleteMember } = familyStore.useDeleteMember()
            const result = await deleteMember(row.id)
            if (result?.data?.code === 200) {
              message.success('删除成功')
              // 删除成功后刷新列表
              await refetchMembers()
            } else {
              message.error(result?.data?.msg || '删除失败')
            }
          } catch (error) {
            message.error('删除失败')
            console.error('删除失败:', error)
          }
        }
      })
    }
    
    return {
      familyStore,
      familyTreeStore,
      dialogVisible,
      selectedMember,
      relatives,
      loading,
      selectedFamilyTree,
      formatDate,
      handleAdd,
      handleEdit,
      handleViewRelatives,
      handleDelete,
      onFamilyTreeChange,
      refresh
    }
  }
}
</script>

<style scoped>
.family-member-list {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.member-info h3 {
  margin-bottom: 20px;
}

.children-section {
  margin-top: 20px;
}

.children-section h4 {
  margin-bottom: 10px;
}
</style>